package org.hang.gift.listener;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.hang.gift.constants.OrderConstants;
import org.hang.gift.dto.PlaceOrderDto;
import org.hang.gift.mapper.GoodsSkuMapper;
import org.hang.gift.service.IGoodsSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 下订单的时候,锁定库存
 */
@Component
@RocketMQMessageListener(topic = OrderConstants.PLACE_ORDER_TX_TOPIC,
consumerGroup = OrderConstants.PLACE_ORDER_TX_LOCK_STOCK_CONSUMER_GROUP)
public class PlaceOrderLockStockMessageListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IGoodsSkuService goodsSkuService;

    /**
     * 执行锁定库存的操作
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        //获取消息
        String s = new String(messageExt.getBody());
        PlaceOrderDto dto = JSONObject.parseObject(s, PlaceOrderDto.class);

        //这个地方不能使用分布式锁，因为即使加了锁，还是会出现前者锁定库存的值被后者锁定库存的值 覆盖的情况
        //数据库在执行这行代码时，会对数据中的当前行数据加行锁，一次只允许一个人修改 锁定库存 的值
        goodsSkuService.lockStock(dto.getSkuInfos());
       }


}
